package com.spring.common.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.oa.api.web.dao.OaMapper;
import com.spring.appservice.web.dao.MainShowMapper;
import com.spring.common.web.dao.CommonApiMapper;
import com.spring.common.web.dao.ContractMapper;
import com.spring.common.web.dao.CrmContactMapper;
import com.spring.common.web.model.KidsPark;
import com.spring.common.web.model.Region;
import com.spring.common.web.requestModel.ProductPromotion;
import com.spring.common.web.service.CommonService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UpdateMap;
import com.spring.security.web.dao.CommonMapper;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoFamily2;
@Service
public class CommonServiceImpl  implements CommonService{
	@Resource
	private CommonApiMapper commonApiMapper;
	
    @Resource
    private JedisCache jedisCache;
	
    @Resource
	private CommonMapper commonMapper;
    
    @Resource
	private OaMapper oaMapper;
    
    @Resource
	private SsoMapper ssoMapper;
    
	@Resource 
	private MainShowMapper mainShowMapper;
	
	@Resource 
	private ContractMapper contractMapper;
	
	@Resource 
	private CrmContactMapper crmContactMapper;
	//@Resource private MainShowService mainShowService;	
    
	//获取某个服务项理论介绍
	@Override
	public Map<String, Object> getServiceIntroduction(String service_type_code) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();
		String introduction= commonApiMapper.getServiceIntroduction(service_type_code);
		List list=new ArrayList();
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("introduction", introduction);
		list.add(hm);
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "取数成功");
		return m;
	}
    
    
    
	//获取所有区域信息
	@Override
	public Map<String, Object> getRegionList() throws Exception{
		Map<String, Object> m = new HashMap();
		List<Region> list = commonApiMapper.getRegionList();
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "取数成功");
		return m;
	}
	
	//获取子区域信息
		@Override
		public Map<String, Object> getChildrenRegionList(String id) throws Exception{
			Map<String, Object> m = new HashMap();
			List<Region> list = commonApiMapper.getChildrenRegionList(id);
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");
			return m;
		}
		
		
		//根据区域id获取乐园信息
	   @Override
	   public Map<String, Object> getKidsParkList(String id) throws Exception{
		   	Map<String, Object> m = new HashMap();
	   		List<KidsPark> list = commonApiMapper.getKidsParkList(id);
	   		m.put(ApplicationUtils.DATASET, list);
	   		m.put(ApplicationUtils.STATUS, "1");
	   		m.put(ApplicationUtils.MSG, "取数成功");
		   	return m;
	   }
	   
	// 获取数字字典
		@Override
		public Map<String, Object> getDataDictionaryList(String type) {
			// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap<String, Object>();
			try {

				if (!ApplicationUtils.isNotNull(type)) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请输入类型");
					return m;
				}

				UpdateMap sel = new UpdateMap("base_type_code");
				sel.addWhere("type", type);
				List<Map<String,Object>> list = commonMapper.select(sel);
				List<Map<String,Object>> nlist = new ArrayList<Map<String,Object>>();
				for(Map<String,Object> d:list){
					d.remove("id");
					nlist.add(d);
				}
				
//				String[] fields = {"id","userId","username","value","reDesc","createTime"};
//				BeanUtil.bean2Map(Map.class, list, fields);
//				List<DataDictionary> list = memberCardApiMapper
//						.getDataDictionaryList(type);
				m.put(ApplicationUtils.DATASET, nlist);
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "取数成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}

		@Override
		public List<Map<String, Object>> checkFilesToken(String token) {
			return commonApiMapper.checkFilesToken(token);
		}
		
		@Override
		public List<Map<String, Object>> checkVideosToken(String token) {
			return commonApiMapper.checkVideosToken(token);
		}

		@Override
		public List<Map<String, Object>> queryFileById(String id) {
			return commonApiMapper.queryFileById(id);
		}

		@Override
		public int addOssFile(Map<String, Object> m) {
			return commonApiMapper.addOssFile(m);
		}
		
		@Override
		public int updateOssFile(Map<String, Object> m) {
			return commonApiMapper.updateOssFile(m);
		}

		@Override
		public int addVideosFile(Map<String, Object> im) {
			return commonApiMapper.addVideosFile(im);
		}
		

		@Override
		public int updateVideosFile(Map<String, Object> im) {
			return commonApiMapper.updateVideosFile(im);
		}
		
		@Override
	    public Map<String, Object> getBannerList(String bannerType) throws Exception{
	   		Map<String, Object> m = new HashMap();
	   		HashMap hm=new HashMap();
	   		hm.put("bannerType", bannerType);
	   		List<Map<String, Object>> list = commonApiMapper.getBannerList(hm);
	   		m.put(ApplicationUtils.DATASET, list);
	   		m.put(ApplicationUtils.STATUS, "1");
	   		m.put(ApplicationUtils.MSG, "取数成功");
	   		return m;
	    }
		
		/**
		 * 查询OA部门
		 */
		@Override
		public List<Map<String, Object>> queryDepartmentPark(String dept_id) {
			Map<String,Object> sp = new HashMap<String,Object>();
			sp.put("dept_id", dept_id);
			List<Map<String, Object>> m = oaMapper.queryDepartmentPark(sp);
			List<Map<String, Object>> parm = new ArrayList<Map<String, Object>>();
			for(Map<String, Object> model:m){
				parm.add(model);
			}
			if(ApplicationUtils.isNotNull(dept_id)){
				getDeptChildrenByPidAll(m,parm);
			}else{
				getDeptChildrenByPid(m,parm);
			}
			return  m;
		}
		
		
		/**
		 * 递归查出部门父节点的子部门节点
		 * @param m
		 */
		private void getDeptChildrenByPid(List<Map<String, Object>> m,List<Map<String, Object>> nparm){
			if(m!=null&&m.size()>0){
				Map<String,Object> parm = new HashMap<String,Object>();
				String dept_id = "";
				for(Map<String, Object> model:nparm){
					dept_id = ApplicationUtils.Object2String(model.get("id"));
					if(ApplicationUtils.isNotNull(dept_id)){
						parm.put("dept_id", dept_id);
						List<Map<String, Object>> cm = oaMapper.queryDepartmentParkChildren(parm);
						if(cm!=null&&cm.size()>0){
							model.put("items",cm);
							getDeptChildrenByPid(m,cm);
						}
					}
				}
			}
		}
		
		/**
		 * 递归查出部门父节点的子部门节点
		 * @param m
		 */
		private void getDeptChildrenByPidAll(List<Map<String, Object>> m,List<Map<String, Object>> nparm){
			if(m!=null&&m.size()>0){
				Map<String,Object> parm = new HashMap<String,Object>();
				String dept_id = "";
				for(Map<String, Object> model:nparm){
					dept_id = ApplicationUtils.Object2String(model.get("id"));
					if(ApplicationUtils.isNotNull(dept_id)){
						parm.put("dept_id", dept_id);
						List<Map<String, Object>> cm = oaMapper.queryDepartmentParkChildrenAll(parm);
						if(cm!=null&&cm.size()>0){
							model.put("items",cm);
							getDeptChildrenByPid(m,cm);
						}
					}
				}
			}
		}

		@Override
		public List<Map<String, Object>> queryUserByDeptId(String dept_id,String shopDeptId,String priv_id) {
			Map<String,Object> sp = new HashMap<String,Object>();
			if(ApplicationUtils.isNotNull(dept_id)){
				sp.put("dept_id", dept_id);
				return oaMapper.queryUserByDeptId(sp);
			}else if(ApplicationUtils.isNotNull(shopDeptId)&&ApplicationUtils.isNotNull(priv_id)){
				sp.put("dept_id", shopDeptId);
				sp.put("dept_name_py", priv_id);
				/**
				 * 查询所有子部门
				 */
				List<Map<String,Object>> rl = oaMapper.queryDepartmentPark(sp);
				List<Map<String,Object>> retl = new ArrayList<Map<String,Object>>();
				for(Map<String,Object> m:rl){
					retl.add(m);
				}
				queryAllDeptByParentList(retl,rl);
				String deptIDs = "";
				for(Map<String,Object> retm:retl){
					deptIDs+=ApplicationUtils.Object2String(retm.get("id"))+",";
				}
				if(ApplicationUtils.isNotNull(deptIDs)){
					sp.put("dept_id", deptIDs.substring(0,deptIDs.length()-1));
				}
				
				return oaMapper.queryUserByDeptId(sp);
			}else{
				return new ArrayList<Map<String,Object>>();
			}
		}
		
		/**
		 * 递归子部门
		 * @param rl
		 * @param parml
		 */
		private void queryAllDeptByParentList(List<Map<String,Object>> rl,
					List<Map<String,Object>> parml){
			List<Map<String,Object>> parmN = new ArrayList<Map<String,Object>>();
			if(parml!=null&&parml.size()>0){
				Map<String,Object> pm = new HashMap<String,Object>();
				for(Map<String,Object> model:parml){
					pm.put("dept_id", model.get("id"));
					List<Map<String,Object>> nl = oaMapper.queryDepartmentParkChildrenAll(pm);
					for(Map<String,Object> nm:nl){
						parmN.add(nm);
						rl.add(nm);
					}
				}
				queryAllDeptByParentList(rl,parmN);
			}
			
		}
		
		
		@Override
		public List<Map<String, Object>> queryCustomerSelByOaUser(String oaUserId) {
			List<Map<String, Object>> m = commonApiMapper.queryCustomerSelByOaUser(oaUserId);
			return  m;
		}
		
		@Override
		public String getKidParkIDByDeptID(String deptID) {
			String kids_park_id = commonApiMapper.getKidParkIDByDeptID(deptID);
			return kids_park_id;
		}
		
		
		
		@Override
		public Map<String, Object> getBusinessTypeCode() {
			Map<String, Object> m = new HashMap<String, Object>();
			
			List<Map<String, Object>> list = commonApiMapper.getBusinessTypeCode();
			
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");
			return m;

		}
		
		@Override
		public List<Map<String, Object>> getBusinessTypeCode2() {			
			List<Map<String, Object>> list = commonApiMapper.getBusinessTypeCode();
			return list;

		}
		
		@Override
		public Map<String, Object> addUser(RequestUser user) throws Exception{
			//在没有提供手机号的情况下，用户名用uuid代替，即不可登入
			String random_user_name = ApplicationUtils.randomUUID();
			
			if(user.getMember_name()==null||user.getMember_name().equals("")){
				user.setMember_name(user.getReal_name());
			}
			if(user.getUserName()==null||user.getUserName().equals("")){
				if(ApplicationUtils.isNotNull(user.getPhone())){
					user.setUserName(user.getPhone());
				}else{
					user.setUserName(random_user_name);
				}
			}
			
			Map<String, Object> m = new HashMap<String, Object>();
			
//			if(user.getC_role_id()!=null||!user.getSex_code().equals("")){
//			if(user.getC_role_id().equals("1")){
//				user.setSex_code("1");
//			}
//			if(user.getC_role_id().equals("2")){
//				user.setSex_code("2");
//			}
//			}else{
//				user.setSex_code("1");
//			}
			
			HashMap<String,Object> family=new HashMap<String,Object> ();
			
			family.put("family_name", user.getPhone()+"用户家庭");
			family.put("wx_point", 0);
			String c_familyID=ApplicationUtils.randomUUID();
			family.put("id", c_familyID);
			
			family.put("phone", user.getPhone());
			family.put("address", user.getAddress());
			family.put("zipcode", user.getZipcode());
			family.put("family_phone", user.getFamily_phone());		

			
			if(user.getC_user_id()==null){
				String c_user_id=ApplicationUtils.randomUUID();
				user.setC_user_id(c_user_id);
			}
			
			//user.setC_family_id(c_familyID);
			
			if(user.getPhone()!=null){
				HashMap<String, Object> h1=new HashMap<String, Object>();
				h1.put("phone", user.getPhone());
				int count=ssoMapper.getUserCountByPhone(h1);
				if(count>0){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "手机号重复");
					return m;
				}
			}
	
			if(user.getC_family_id()==null){
				int effect=ssoMapper.insertFamily(family);
				if(effect!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "插入家庭失败");
					throw new Exception();
				}			
			}
			//如果没有家庭号生成家庭号然后设置新家庭号
			if(user.getC_family_id()==null){
				user.setC_family_id(c_familyID);
			}
			
			
			int effect2=ssoMapper.insertUser(user);
			if(effect2!=1){
				throw new Exception();
			}	
				
			HashMap<String,Object> hm=new HashMap<String,Object>();
			hm.put("c_familyID", c_familyID);
			hm.put("c_user_id",user.getC_user_id() );		
			
			m.put(ApplicationUtils.DATASET, hm);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "插入成功");


			return m;
		}
				
		
		@Override
		public Map<String, Object> saveOrUpdateProductPromotion(ProductPromotion  productPromotion) throws Exception {
			
				Map<String, Object> m = new HashMap();

				String[] orderProductID= commonApiMapper.getOrderProductID(productPromotion.getProductCode());
				if(orderProductID==null||orderProductID.length==0){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该产品code无效");
					return m;
				}
				if(orderProductID.length>1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "该产品code对应多个产品，正常情况下一个code只能对应一个产品，请检查数据库数据的正确性");
					return m;
				}
				
				
				productPromotion.setOrder_productID(orderProductID[0]);

				if(productPromotion.getProductPromotionID()==null||productPromotion.getProductPromotionID().equals("")){
					String productPromotionID=ApplicationUtils.randomUUID();	
					productPromotion.setProductPromotionID(productPromotionID);
					
					int effect=commonApiMapper.insertProductPromotion(productPromotion);
					if(effect<1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "修改失败");
						return m;
					}
					
				}else{
					int effect2=commonApiMapper.updateProductPromotion(productPromotion);
					if(effect2<1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "修改失败");
						return m;
					}
				}
				List list=new ArrayList();
				Map<String, Object> hm = new HashMap();
				hm.put("productPromotionID", productPromotion.getProductPromotionID());
				list.add(hm);

				m.put(ApplicationUtils.DATASET, list);	
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "修改成功");

			
			return m;
		}
		
		@Override
		public Map<String, Object> getFamilyDetail(String phone,String card_number,String member_number,String c_user_id) throws Exception {
			Map<String, Object> m = new HashMap();
			
			if((phone==null||phone.equals(""))&&(card_number==null||card_number.equals(""))&&(member_number==null||member_number.equals(""))&&
					(c_user_id==null||c_user_id.equals(""))){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入查询条件");
				return m;
			}
						
			HashMap<String,Object> hm=new HashMap<String,Object>();
			hm.put("phone", phone);
			hm.put("card_number", card_number);
			hm.put("member_number", member_number);
			hm.put("c_user_id", c_user_id);
			
			List<SsoFamily2> list = ssoMapper.getFamilyDetail2(hm);

			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}
		
		
		@Override
		public Map<String, Object> checkFingerExist(String c_user_id) throws Exception {
			Map<String, Object> m = new HashMap();
			
			String isFingerExist = ssoMapper.checkFingerExist(c_user_id);
			
			HashMap<String,Object> hm=new HashMap<String,Object>();
			hm.put("isFingerExist", isFingerExist);
						
			m.put(ApplicationUtils.DATASET, hm);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}
		
		@Override
		public BaseResult updateReadCount(String id,String type){
			BaseResult b=null;
			int effect=0;
			switch(type)
			{
			case "1":
				effect=mainShowMapper.updateNewsCount(id);
				break;
			case "2":
				effect=mainShowMapper.updateActivityCount(id);
				break;
			case "3":
				effect=mainShowMapper.updateJournalCount(id);
				break;
			default:
				b=new BaseResult("0","请输入有效type");
				return b;
			}
			if(effect>0){
				b=new BaseResult("1","修改成功");
			}else{
				b=new BaseResult("0","修改失败");
			}
			
			return b;
		}
		
		//	//type 1 news 2 activity 3 myspace
		public void checkIsNewAddr(String id,String type,HttpServletRequest request) throws Exception{
			
			String ipaddr=MyTools.getIpAddr(request);
			
			Boolean b=jedisCache.exists(id+ipaddr);
			if(b==false){
			//if(true){
				Map<String,String> ms = Maps.newHashMap();
				ms.put("1", "1");
				
				jedisCache.hmset(id+ipaddr, ms);
				jedisCache.expire(id+ipaddr, 60*60);

				this.updateReadCount(id, type);
			}
		}
		
		@Override
		public BaseResult updatePhone(String cUserID,String newPhone) throws Exception{
			HashMap<String,Object> param=new HashMap<String,Object>();
			param.put("cUserID", cUserID);
			param.put("newPhone", newPhone);
			
			int effect = contractMapper.updatePhone(param);			
			//MyTools.checkEffect(effect);			
			int effect2 = crmContactMapper.updatePhone(param);
			//MyTools.checkEffect(effect2);	
			
			return new BaseResult();
		};
}
